package models.features;

import java.sql.SQLException;
import java.util.Arrays;

import models.util.Area;
import core.User;
import core.database.DataBaseManager;

public class Statistics {

	private User currentUser;
	private static Statistics instance;

	public static Statistics newInstance(User u) {
		if (instance == null)
			instance = new Statistics(u);
		return instance;
	}

	private Statistics(User u) {
		currentUser = u;
	}

	public int[] getStatisticValues() {
		// int[]v = {100,200,350,212,124,1000};
		// return v;
		final int SIZE = 6;
		int[] values = new int[SIZE];
		try {
			for (int i = 0; i < Area.TOTAL_AREAS; i++) {
				int v = getAverage((i + 1), currentUser);
				if (v == -1)
					v = 0;
				values[i] = v;
			}
			values[SIZE - 1] = DataBaseManager.getRecord(currentUser);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Arrays.toString(values));
		return values;
	}

	private static int getAverage(int idArea, User user) throws SQLException {
		int oldAverage = DataBaseManager.getAverage(idArea, user);
		int newAverage = newAverage(idArea, user);
		int average = -1;
		System.out.println("AREA " + idArea + " old " + oldAverage + " new "
				+ newAverage);
		if (newAverage != -1) {
			if (oldAverage != -1)
				average = (oldAverage + newAverage) / 2;
			else
				average = newAverage;
			DataBaseManager.setAverage(idArea, user, average);
		} else
			average = oldAverage;
		return average;
	}

	private static int newAverage(int idArea, User user) throws SQLException {
		int[] scores = DataBaseManager.getAreaScoreSince(idArea, user,
				DataBaseManager.getAverageDate(idArea, user));
		System.out.println("SCORES " + Arrays.toString(scores));
		if (scores == null || scores.length == 0)
			return -1;
		int i = 0;
		int sum = 0;
		while (i < scores.length)
			sum += scores[i++];
		int newAverage = sum / scores.length;
		return newAverage;
	}

}
